package com.webserver.core;

import com.webserver.http.HttpRequest;
import com.webserver.http.HttpResponse;

import java.io.*;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/*
* 处理与指定客户端的HTTP交互
* HTTP交互采取一问一答，因此这里分为三步完成一次交互过程：
* 1.解析请求
* 2.处理请求
* 3.响应客户端
* */
public class ClientHandler implements Runnable{
    private Socket socket;
    public ClientHandler(Socket socket){
        this.socket = socket;
    }
    @Override
    public void run() {
        try {
            /* 1.解析请求*/
            HttpRequest request = new HttpRequest(socket);
            HttpResponse response = new HttpResponse(socket);

            /*2.处理请求*/
            DispatcherServlet servlet = new DispatcherServlet();
            servlet.service(request,response);

            /*3.发送响应*/
            response.flush();
            /*
            * 发送一个标准响应头，大致如下
            * HTTP/1.1 200 OK(CRLF)
            * Content-Type: text/html(CRLF)
            * Content-Length: 2546(CRLF)(CRLF)
            * 1010101010111
            * */
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                //交互完毕后和客户端断开连接
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
